var mongodbclient = require('mongodb').MongoClient

var client = mongodbclient.connect("mongodb://localhost:27017/tts_short_url")
var isconnect = false

//var crypto = require('crypto')

var common = require('./common.js')


module.exports = {
    //初始化数据结构
    async init() {
        const db = await this.db_tts_short_url()
        var appid = "AP" + Date.now() + "" + Math.round(Math.random() * 999) + "" + Math.round(Math.random() * 999)
        var key = Date.now() + "" + Math.round(Math.random() * 999) + "" + Math.round(Math.random() * 999) + "" + Math.round(Math.random() * 999)

        const c = await db.collection("app").countDocuments()
        if (c <= 0) {
            //app集合，保存可操作接口的appid
            db.collection("app").insertOne({
                appid: appid,       //APPID
                appid_key: key,     //KEY
                status: 1,          //1正常，0停用，2禁用
                add_time: new Date()
            })

            //初始化一个short_key的自增值id
            db.collection("short_key").insertOne({
                key_autoid: 1//自增值id
            })

            db.collection("short_url").insertOne({
                url_key: '',           //使用自增值id获得对应的长URL
                url_id:0,
                absolute_url: "https://127.0.0.1:3000/",
                appid: appid,
                exp_time: new Date(),
                add_time: new Date(),
                status: 1,
                num:0   //访问数量
            })

            //查比较频繁的使用url_key
            db.collection("short_url").createIndex('url_key')

        }
    },
    async db_tts_short_url() {
        var result = await client
        if (!isconnect) {
            await result.connect()
            isconnect=true
        }
        return await result.db()
    },
    async db_client() {
        var result = await client
        if (!isconnect) {
            await result.connect()
            isconnect = true
        }
        return result
    },


}